﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;
using System.Threading;

namespace StatusPlan3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Telerik.Windows.Controls.RadRibbonWindow
    {
        Thread loadingThread;
        StatusPlanHandler sph;
        List<RadPane> openProjects;
        RadPane myPage;
        RadPane users;
        RadPane roles;
        RadPane projectGroups;
        List<RadPane> openNewProjects;
        List<RadPane> openProjectTasks;
        List<RadPane> openTasks;
        List<RadPane> newTasks;
        Window_Loading windowLoading;

        public MainWindow()
        {
            
            this.Closed += new EventHandler(MainWindow_Closed);
            StatusPlanData.mainWindow = this;

            openProjects = new List<RadPane>();
            openNewProjects = new List<RadPane>();
            openProjectTasks = new List<RadPane>();
            openTasks = new List<RadPane>();
            newTasks = new List<RadPane>();

            StyleManager.ApplicationTheme = new Office_BlueTheme();
            
            StatusPlanData.statusPlanHandler = new StatusPlanHandler();
            sph = StatusPlanData.statusPlanHandler;

            if (!checkComandLineVariables())
            {
                //LOGIN REGION
                Window_Loading wl = new Window_Loading();
                wl.setMainWindow(this);
                bool? b = wl.showManualLogin();
                if (b != null && b == false)
                {
                    Application.Current.Shutdown();
                }
            }


            DateTime dt = DateTime.Now;
            System.Console.WriteLine("Time start: " + (DateTime.Now - dt).TotalSeconds);

            showLoadingFrame();
            InitializeComponent();

            
            populateFrame();
            System.Console.WriteLine("Time after populateFrame: " + (DateTime.Now - dt).TotalSeconds);
            showMyPage();
            System.Console.WriteLine("Time after showMyPage: " + (DateTime.Now - dt).TotalSeconds);
            closeLoadingFrame();
            System.Console.WriteLine("Time done: " + (DateTime.Now - dt).TotalSeconds);
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            if (System.IO.Directory.Exists("temp"))
            {
                string[] s = System.IO.Directory.GetFiles("temp");
                foreach (String file in s)
                {
                    try
                    {
                        System.IO.File.Delete(file);
                    }
                    catch { }
                }
            }
        }

        public void showLoadingFrame()
        {
            loadingThread = new Thread(showLoadFrame);
            loadingThread.SetApartmentState(ApartmentState.STA);
            loadingThread.Start();
        }

        private void showLoadFrame()
        {
            windowLoading = new Window_Loading();
            windowLoading.showText("Innlesur dáta");
            windowLoading.ShowDialog();
        }

        public void closeLoadingFrame()
        {
            windowLoading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate() { windowLoading.Close(); });
        }

        private Boolean checkComandLineVariables()
        {
            String user = "";
            String password = "";
            Boolean windowAuth = false;

            foreach (String s in Environment.GetCommandLineArgs())
            {
                if (s.ToLower().StartsWith("/u:"))
                {
                    user = s.Substring(3);
                }
                if (s.ToLower().StartsWith("/p:"))
                {
                    password = s.Substring(3);
                }
                if (s.ToLower().StartsWith("/w"))
                {
                    windowAuth = true;
                }
            }

            Boolean b = false;
            if (user.Trim().Length > 0 || password.Trim().Length > 0 || windowAuth)
            {
                b = login(user, password, windowAuth);
                if (!b)
                    MessageBox.Show("Brúkari ella kota er skeiv", "Login: Feilur", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return b;
        }

        public void showRoles()
        {
            if (roles == null)
            {
                RadPane rp = createPane("Rollir");
                roles = rp;

                rp.Content = new StatusPlan3.UC.UCRoles();
                RadPaneGroup1.Items.Add(rp);
                rp.Unloaded += new RoutedEventHandler(showRoles_Unloaded);
            }
            else
            {
                roles.IsSelected = true;
            }
        }

        void showRoles_Unloaded(object sender, RoutedEventArgs e)
        {
            RadPane rp = sender as RadPane;
            if (rp.IsHidden == true)
                roles = null;
        }

        public void showUsers()
        {
            if (users == null)
            {
                RadPane rp = createPane("Brúkarir");
                users = rp;

                rp.Content = new StatusPlan3.UC.UCUsers();
                RadPaneGroup1.Items.Add(rp);
                rp.Unloaded += new RoutedEventHandler(showUsers_Unloaded);
            }
            else
            {
                users.IsSelected = true;
            }
        }

        void showUsers_Unloaded(object sender, RoutedEventArgs e)
        {
            RadPane rp = sender as RadPane;
            if (rp.IsHidden == true)
                users = null;
        }

        public void showAllProjectGroups()
        {
            if (projectGroups == null)
            {
                RadPane rp = createPane("Brúkarir");
                projectGroups = rp;

                rp.Content = new StatusPlan3.UC.UCProjectGroups();
                RadPaneGroup1.Items.Add(rp);
                rp.Unloaded += new RoutedEventHandler(showAllProjectGroups_Unloaded);
            }
            else
            {
                projectGroups.IsSelected = true;
            }
        }

        void showAllProjectGroups_Unloaded(object sender, RoutedEventArgs e)
        {
            RadPane rp = sender as RadPane;
            if (rp.IsHidden == true)
                projectGroups = null;
        }

        public void showTask(Task t, Project p, ProjectGroup pg, Subproject sp = null)
        {
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openTasks)
            {
                UC.UCTask ucTask = panel.Content as UC.UCTask;

                if (ucTask.task.id == t.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane("Task: " + t.name);
                StatusPlan3.UC.UCTask ucTask = new StatusPlan3.UC.UCTask();
                ucTask.rp = rp;
                ucTask.setData(t, p, pg, sp);
                openTasks.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_ProjectTask_Unloaded);
                rp.Content = ucTask;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                orgPane.IsSelected = true;
            }
        }

        void rp_ProjectTask_Unloaded(object sender, RoutedEventArgs e)
        {
            RadPane rp = sender as RadPane;
            if (rp.IsHidden == true)
                openTasks.Remove(rp);
        }

        public void showNewTask(Project p, ProjectGroup pg, Subproject sp = null)
        {
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in newTasks)
            {
                UC.UCTask ucTask = panel.Content as UC.UCTask;

                if (ucTask.project.id == p.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane("Stovna Task í " + p.name);
                StatusPlan3.UC.UCTask ucTask = new StatusPlan3.UC.UCTask();
                ucTask.rp = rp;
                ucTask.showNew(p, pg, sp);
                newTasks.Add(rp);
                rp.Unloaded += new RoutedEventHandler(showNewTask_Unloaded);
                rp.Content = ucTask;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                orgPane.IsSelected = true;
            }
        }

        void showNewTask_Unloaded(object sender, RoutedEventArgs e)
        {
            RadPane rp = sender as RadPane;
            if (rp.IsHidden == true)
                newTasks.Remove(rp);
        }



        public void showTasks(Project p,ProjectGroup pg)
        {
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openProjectTasks)
            {
                UC.UCTasks ucTasks = panel.Content as UC.UCTasks;

                if (ucTasks.project.id == p.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane(p.name + ": Tasks");
                StatusPlan3.UC.UCTasks ucTasks = new StatusPlan3.UC.UCTasks();
                ucTasks.rp = rp;
                ucTasks.setData(p,pg);
                openProjectTasks.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_ProjectTasks_Unloaded);
                rp.Content = ucTasks;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                orgPane.IsSelected = true;
            }
        }

        void rp_ProjectTasks_Unloaded(object sender, RoutedEventArgs e)
        {
            RadPane rp = sender as RadPane;
            if (rp.IsHidden == true)
                openProjectTasks.Remove(rp);
        }



        public void showNewProject(ProjectGroup pg)
        {
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openNewProjects)
            {
                UC.UCProject ucproject = panel.Content as UC.UCProject;
                
                if (ucproject.projectGroup.id == pg.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane(pg.name + ": Nýggj verkætlan");
                StatusPlan3.UC.UCProject ucProject = new StatusPlan3.UC.UCProject();
                ucProject.rp = rp;
                ucProject.showNew(pg);
                openNewProjects.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_NewProject_Unloaded);    
                rp.Content = ucProject;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                orgPane.IsSelected = true;
            }
        }

        void rp_NewProject_Unloaded(object sender, RoutedEventArgs e)
        {
            RadPane rp = sender as RadPane;
            if (rp.IsHidden == true)
                openNewProjects.Remove(rp);
        }

public void showMyPage()
{
    if (myPage == null)
    {
        RadPane rp = createPane("Mín síða");
        myPage = rp;
                
        rp.Content = new StatusPlan3.UC.MyPage();
        RadPaneGroup1.Items.Add(rp);
        rp.Unloaded += new RoutedEventHandler(myPage_Unloaded);
    }
    else
    {
        myPage.IsSelected = true;
    }
}

        void myPage_Unloaded(object sender, RoutedEventArgs e)
        {
            if (myPage.IsHidden == true)
            {
                myPage = null;
            }
        }



        private void showProjectGroup()
        {
            ProjectGroup p = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openProjects)
            {
                UC.UCProjectGroup ucproject = panel.Content as UC.UCProjectGroup;
                if (ucproject.projectGroup.id == p.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane(p.name);
                StatusPlan3.UC.UCProjectGroup ucProject = new StatusPlan3.UC.UCProjectGroup();
                ucProject.showProjects();
                ucProject.setData(p);
                openProjects.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_Unloaded);
                rp.Content = ucProject;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                UC.UCProjectGroup ucProject = orgPane.Content as UC.UCProjectGroup;
                ucProject.showProjects();
                orgPane.IsSelected = true;
            }
        }

        private void showProjectMembers()
        {
            ProjectGroup p = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openProjects)
            {
                UC.UCProjectGroup ucproject = panel.Content as UC.UCProjectGroup;
                if (ucproject.projectGroup.id == p.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane(p.name);
                StatusPlan3.UC.UCProjectGroup ucProject = new StatusPlan3.UC.UCProjectGroup();
                ucProject.showMembers();
                ucProject.setData(p);
                openProjects.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_Unloaded);
                rp.Content = ucProject;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                UC.UCProjectGroup ucProject = orgPane.Content as UC.UCProjectGroup;
                ucProject.showMembers();
                orgPane.IsSelected = true;
            }
        }

        private void showProjectPriorities()
        {
            ProjectGroup p = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openProjects)
            {
                UC.UCProjectGroup ucproject = panel.Content as UC.UCProjectGroup;
                if (ucproject.projectGroup.id == p.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane(p.name);
                StatusPlan3.UC.UCProjectGroup ucProject = new StatusPlan3.UC.UCProjectGroup();
                ucProject.showPriorities();
                ucProject.setData(p);
                openProjects.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_Unloaded);
                rp.Content = ucProject;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                UC.UCProjectGroup ucProject = orgPane.Content as UC.UCProjectGroup;
                ucProject.showPriorities();
                orgPane.IsSelected = true;
            }
        }

        private void showProjectStates()
        {
            ProjectGroup p = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openProjects)
            {
                UC.UCProjectGroup ucproject = panel.Content as UC.UCProjectGroup;
                if (ucproject.projectGroup.id == p.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane(p.name);
                StatusPlan3.UC.UCProjectGroup ucProject = new StatusPlan3.UC.UCProjectGroup();
                ucProject.showStates();
                ucProject.setData(p);
                openProjects.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_Unloaded);
                rp.Content = ucProject;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                UC.UCProjectGroup ucProject = orgPane.Content as UC.UCProjectGroup;
                ucProject.showStates();
                orgPane.IsSelected = true;
            }
        }

        private void showProjectTypes()
        {
            ProjectGroup p = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            Boolean alreadyOpen = false;
            RadPane orgPane = null;
            foreach (var panel in openProjects)
            {
                UC.UCProjectGroup ucproject = panel.Content as UC.UCProjectGroup;
                if (ucproject.projectGroup.id == p.id)
                {
                    alreadyOpen = true;
                    orgPane = panel;
                    break;
                }
            }

            if (!alreadyOpen)
            {
                RadPane rp = createPane(p.name);
                StatusPlan3.UC.UCProjectGroup ucProject = new StatusPlan3.UC.UCProjectGroup();
                ucProject.showTypes();
                ucProject.setData(p);
                openProjects.Add(rp);
                rp.Unloaded += new RoutedEventHandler(rp_Unloaded);
                rp.Content = ucProject;
                RadPaneGroup1.Items.Add(rp);
            }
            else
            {
                UC.UCProjectGroup ucProject = orgPane.Content as UC.UCProjectGroup;
                ucProject.showTypes();
                orgPane.IsSelected = true;
            }
        }

        internal void refreshProjectGroup(int id)
        {
            foreach (var panel in openProjects)
            {
                UC.UCProjectGroup ucproject = panel.Content as UC.UCProjectGroup;
                if (ucproject.projectGroup.id == id)
                {
                    ucproject.refreshFrame();
                    break;
                }
            }
        }

        void rp_Unloaded(object sender, RoutedEventArgs e)
        {
            
            RadPane rp = sender as RadPane;
            if(rp.IsHidden == true) 
                openProjects.Remove(rp);
        }

        public void populateFrame()
        {
            ProjectGroups pgs = StatusPlanData.statusPlanHandler.getProjectGroups(StatusPlanData.currentUser.id);
            ComboBox_ProjectGroup.ItemsSource = pgs;
            ComboBox_ProjectGroup.DisplayMemberPath = "name";

            if (StatusPlanData.currentUser.userStandard != null)
            {
                if (StatusPlanData.currentUser.userStandard.projectGroup_id != null)
                {
                    foreach (var pg in pgs)
                    {
                        if (pg.id == StatusPlanData.currentUser.userStandard.projectGroup_id)
                        {
                            ComboBox_ProjectGroup.SelectedItem = pg;
                            break;
                        }
                    }

                    if (StatusPlanData.currentUser.userStandard.project_id != null)
                    {
                        foreach (Project p in ComboBox_Project.Items)
                        {
                            if (p.id == StatusPlanData.currentUser.userStandard.project_id)
                            {
                                ComboBox_Project.SelectedItem = p;
                                break;
                            }
                        }
                    }
                }
            }
        }

        private void ProjectGroupChanged(ProjectGroup pg)
        {
            ComboBox_Project.ItemsSource = pg.projects;
            ComboBox_Project.DisplayMemberPath = "name";
            
            if (pg != null)
            {
                ComboBox_Project.ItemsSource = StatusPlanData.statusPlanHandler.getProjects(pg.id);
                ComboBox_Project.IsEnabled = true;
                RibbonGroup_ProjectGroup.IsEnabled = true;
                RibbonGroup_ProjectGroup.Header = pg.name;
            }
            else
            {
                ComboBox_Project.IsEnabled = false;
                ComboBox_Project.SelectedItem = null;
                RibbonGroup_ProjectGroup.IsEnabled = false;
                RibbonGroup_ProjectGroup.Header = "";
            }
        }

        private void ProjectChanged(Project p)
        {
            if (p != null)
            {
                RibbonGroup_General.IsEnabled = true;
                RibbonGroup_General.Header = p.name;
            }
            else
            {
                RibbonGroup_General.IsEnabled = false;
                RibbonGroup_General.Header = "";
            }
        }

        public Boolean login(String name, String password, Boolean winAuth = false)
        {
            return sph.login(name, password,winAuth);
        }

        private void RadRibbonButton_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Button_SetAsStandard_Click(object sender, RoutedEventArgs e)
        {
            ProjectGroup pg = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            if (pg != null)
            {
                Project p = ComboBox_Project.SelectedItem as Project;
                String message = "Er tú vís/ur í at tú vilt seta ";
                if (pg != null)
                    message += "bólkin: " + pg.name;
                if (p != null)
                    message += " og verkætlanina: " + p.name;

                message += " sum standard?";
                if (MessageBox.Show(message, "Set sum standard", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    StatusPlanData.statusPlanHandler.setAsStandard(pg, p);
                    MessageBox.Show("Standur goymdur", "Set sum standard", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        private RadPane createPane(String name)
        {
            RadPane rp = new RadPane();
            rp.Header = name;
            rp.ContextMenuTemplate = null;
            rp.CanFloat = true;
            rp.CanUserPin = false;

            return rp;
        }

        private void ComboBox_ProjectGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ProjectGroup pg = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            if (pg != null)
            {
                ProjectGroupChanged(pg);
            }
            else
            {
                ComboBox_Project.IsEnabled = false;
            }
        }

        private void Button_SetAsStandard_Click(object sender, EventArgs e)
        {
            MessageBox.Show("HEY");
        }

        private void ComboBox_Project_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Project p = ComboBox_Project.SelectedItem as Project;
            if (p != null)
            {
                
                ProjectChanged(p);
            }
            else
            {
                RibbonGroup_General.IsEnabled = false;
            }
        }

        private void ProjectButton_Click(object sender, RoutedEventArgs e)
        {
            showProjectGroup();
        }

        private void MyPageButton_Click(object sender, RoutedEventArgs e)
        {
            showMyPage();
        }

        private void ProjectButton_Click2(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            showNewProject(ComboBox_ProjectGroup.SelectedItem as ProjectGroup);
        }

        private void RadRibbonSplitButton_Click(object sender, RoutedEventArgs e)
        {
            showTasks(ComboBox_Project.SelectedItem as Project, ComboBox_ProjectGroup.SelectedItem as ProjectGroup);
        }

        private void TopBar_HelpRequested(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            System.Windows.Forms.Help.ShowHelp(null, "SP3help.chm", System.Windows.Forms.HelpNavigator.TopicId, "20");
        }

        private void RadRibbonButton_Click_1(object sender, RoutedEventArgs e)
        {
            showProjectTypes();
        }

        private void RadRibbonButton_Click_2(object sender, RoutedEventArgs e)
        {
            showProjectStates();
        }

        private void RadRibbonButton_Click_3(object sender, RoutedEventArgs e)
        {
            showProjectPriorities();
        }

        private void RadRibbonButton_Click_4(object sender, RoutedEventArgs e)
        {
            showProjectTypes();
        }

        private void RadRibbonButton_Click_5(object sender, RoutedEventArgs e)
        {
            showProjectStates();
        }

        private void RadRibbonButton_Click_6(object sender, RoutedEventArgs e)
        {
            showProjectMembers();
        }

        private void RadRibbonButton_Click_7(object sender, RoutedEventArgs e)
        {
            showUsers();
        }

        private void RadRibbonButton_Click_8(object sender, RoutedEventArgs e)
        {
            showRoles();
        }

        private void RadRibbonButton_Click_9(object sender, RoutedEventArgs e)
        {
            showAllProjectGroups();
        }

        private void ComboBox_ProjectGroup_PreviewDrop(object sender, DragEventArgs e)
        {
            
        }

        private void ComboBox_Project_PreviewDrop(object sender, DragEventArgs e)
        {
            
        }

        private void ComboBox_ProjectGroup_MouseEnter(object sender, MouseEventArgs e)
        {
            //ComboBox_ProjectGroup.ItemsSource = StatusPlanData.statusPlanHandler.getProjectGroups(StatusPlanData.currentUser.id);
            //ComboBox_ProjectGroup.DisplayMemberPath = "name";
        }

        private void ComboBox_Project_MouseEnter(object sender, MouseEventArgs e)
        {
            //ProjectGroup pg = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            //if (pg != null)
            //{
            //    ComboBox_Project.ItemsSource = pg.projects;
            //    ComboBox_Project.DisplayMemberPath = "name";
            //}
        }

        private void RadMenuItem_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            ProjectGroup pg = ComboBox_ProjectGroup.SelectedItem as ProjectGroup;
            Project p = ComboBox_Project.SelectedItem as Project;
            if(pg != null && p != null) 
                showNewTask(p,pg);
        }        
    }
}
